package com.android.functionmanagement.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;

import com.android.functionmanagement.BaseActivity;
import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.service.AlertService;
import com.android.functionmanagement.service.CallService;
import com.android.functionmanagement.util.AlertUtil;
import com.android.functionmanagement.util.DeviceUtils;
import com.android.functionmanagement.util.JSONUtil;
import com.android.functionmanagement.util.SharedPreferencesUtils;
import com.uwatch.helowin.R;

import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

public class SosActivity extends BaseActivity {

	private final static int MSG_CANCEL_RING = 0x1001;
	private final static int MSG_CANCEL_REC = 0x1002;
	private final static int MSG_CALL_ONES = 0x1003;
//	private Ringtone mRingtone;
	private int mRingId = -1;
	private MediaRecorder myRecorder;
	private String[] mNumList;
	protected int mDialIndex;
	private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
		int mPreCallState = TelephonyManager.CALL_STATE_IDLE;

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.telephony.PhoneStateListener#onCallStateChanged(int,
		 * java.lang.String)
		 */
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				if (TelephonyManager.CALL_STATE_OFFHOOK == mPreCallState
						&& mNumList != null && mNumList.length > 0
						&& !mIsConnected) {
					if (2 == (mDialIndex) / mNumList.length)
						finish();
					else {
						mHandler.sendEmptyMessageDelayed(MSG_CALL_ONES, 2000);
						SharedPreferencesUtils.setParam(SosActivity.this,
								"SOS_ALERT", true);
					}
				}
				break;

			case TelephonyManager.CALL_STATE_RINGING:

				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:

				break;
			}
			mPreCallState = state;
		}
	};
	private boolean mIsConnected;

	@Override
	protected void onNewIntent(Intent intent) {
		mIsConnected = intent.getBooleanExtra("SOS_ACTIVED", false);
		Log.i("DHYCO", "SOS_ACTIVED = " + mIsConnected);
		if (mIsConnected)
			finish();
	};

	private Handler mHandler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {

			switch (msg.what) {
			case MSG_CANCEL_REC:
				stopRecording();
				break;
			case MSG_CANCEL_RING:
				cancelAlert();
				startRecording();
				mDialIndex = 0;
				pushMsg();
				upLoadPush();
				break;
			case MSG_CALL_ONES:
				pushMsg();
				break;
			default:
				break;
			}
		};
	};

	void pushMsg() {
		if (mNumList != null && mNumList.length > 0) {
			Intent intent = new Intent(this, CallService.class);
			intent.putExtra("NUMBER_INDEX",mDialIndex);
			intent.putExtra("NUMBER_LEN",mNumList.length);
			startService(intent);
			
			String number = mNumList[(mDialIndex++) % mNumList.length];
			String num = DeviceUtils.getNumber(SosActivity.this);
			String user = SharedPreferencesUtils.getParam(SosActivity.this,
					ConstantGloble.USERNAME, num).toString();
			String message = getString(R.string.alert_sms_no_number, user,
					DeviceUtils.formatDate(new Date(), "yyyy年MM月dd日HH点mm分"));
			if (!"".equals(num))
				message = getString(
						R.string.alert_sms,
						user,
						DeviceUtils.formatDate(new Date(), "yyyy年MM月dd日HH点mm分"),
						num);
			if (mDialIndex <= mNumList.length)
				sendSMS(number, message);
			dailCall(number);
		}
		
	}

	/**
	 * 
	 */
	protected void upLoadPush() {
		// TODO Auto-generated method stub
		//if (!isWifiConnected())
		//	return;
		Intent in = new Intent(this, AlertService.class);
		in.putExtra(ConstantGloble.ALARMACTION,
				ConstantGloble.SOS_REQUEST_LOCATION);
		startService(in);
		Log.i("DHYCO", "dhyco,,,,,DIALING ..*&^&...SOS_REQUEST_LOCATION");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate(Bundle bundle) {
		// TODO Auto-generated method stub
		super.onCreate(bundle);
		setContentView(R.layout.sos_alert_layout);
		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getFamilyNumbers();
		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		mRingId = AlertUtil.getInstance().load(this,R.raw.sos_alert,-1,0);
//		mRingtone = RingtoneManager.getRingtone(this,
//				RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
//		mRingtone.play();
		mHandler.sendEmptyMessageDelayed(MSG_CANCEL_RING, 10 * 1000);
	}

	@SuppressWarnings("unchecked")
	private void getFamilyNumbers() {
		String dataStrings = SharedPreferencesUtils.getParam(this,
				"numberList", "").toString();
		dataStrings = dataStrings.replace("}, {", "},{").replace("=", "=\"")
				.replace(", ", "\", ").replace("}", "\"}")
				.replace("},{", "}, {");
		try {
			ArrayList<HashMap<String, Object>> datas = (ArrayList<HashMap<String, Object>>) JSONUtil
					.parseJsonResponse(dataStrings);
			if (datas == null)
				return;
			mNumList = new String[datas.size()];
			for (int i = 0; i < mNumList.length; i++) {
				mNumList[i] = "" + datas.get(i).get(ConstantGloble.MOBILE);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param v
	 */
	public void onClick(View v) {
		finish();
	}

	private void startRecording() {
		myRecorder = new MediaRecorder();
		// 从麦克风源进行录音
		myRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
		// 设置输出格式
		myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		// 设置编码格式
		myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			try {
				String path = Environment.getExternalStorageDirectory()
						.getCanonicalPath().toString()
						+ "/SosRecordingFiles";
				File files = new File(path);
				if (!files.exists()) {
					if (!files.mkdir())
						return;
				}
				String paths = path + "/sosAudio.3gp";
				File saveFilePath = new File(paths);
				myRecorder.setOutputFile(saveFilePath.getAbsolutePath());
				saveFilePath.createNewFile();
				myRecorder.prepare();
				// 开始录音
				myRecorder.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		mHandler.sendEmptyMessageDelayed(MSG_CANCEL_REC, 10 * 1000);
	}

	private void stopRecording() {
		mHandler.removeMessages(MSG_CANCEL_REC);
		if (myRecorder == null)
			return;
		myRecorder.stop();
		myRecorder.release();
		myRecorder = null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		mHandler.removeMessages(MSG_CALL_ONES);
		cancelAlert();
		stopRecording();
		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
	}



	/**
	 * 发送短信到central number
	 * 
	 * 直接调用短信接口发短信
	 * 
	 * @param phoneNumber
	 * @param message
	 */
	private void sendSMS(String phoneNumber, String message) {
		if (TextUtils.isEmpty(phoneNumber))
			return;
		// 获取短信管理器
		SmsManager smsManager = SmsManager.getDefault();
		// 拆分短信内容（手机短信长度限制）
		List<String> divideContents = smsManager.divideMessage(message);
		for (String text : divideContents) {
			smsManager.sendTextMessage(phoneNumber, null, text, null, null);
		}
	}

	/**
	 * 拨打号码
	 * 
	 * @param phoneNum
	 */
	private void dailCall(String phoneNum) {
		Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
				+ phoneNum));
		callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(callIntent);
	}

	private void cancelAlert() {
		mHandler.removeMessages(MSG_CANCEL_RING);
		if(mRingId != -1)
			AlertUtil.getInstance().stop(mRingId);
		mRingId = -1;
//		if (mRingtone != null)
//			mRingtone.stop();
//		mRingtone = null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mNumList != null && mNumList.length > 0
				&& 2 > (mDialIndex) / mNumList.length && !mIsConnected)
			stopService(new Intent(this, CallService.class));
	}
	
	private boolean isWifiConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		State wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		NetworkInfo info = cm.getActiveNetworkInfo();
		return (wifiState != null && State.CONNECTED == wifiState)
				&& (info != null && info.isConnected() && info.isAvailable());
	}
}
